package com.itcs.box.server.server;

import com.itcs.box.server.service.NettyMsgResolveService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 消息通道Handler
 * 
 * @author LiuPeng
 * 
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

	private Log logger = LogFactory.getLog(getClass());

	private NettyMsgResolveService nettyMsgResolveService;

	public NettyServerHandler(NettyMsgResolveService nettyMsgResolveService) {
		this.nettyMsgResolveService = nettyMsgResolveService;
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent e = (IdleStateEvent) evt;
			switch (e.state()) {
			case READER_IDLE:
				String deviceId = NettyChannelMap.getKeyByValue(ctx);
				if (deviceId == null) {
					deviceId = ctx.channel().remoteAddress().toString();
				}
				ctx.disconnect();
				ctx.close();
				logger.warn("客户端:" + deviceId + " 长时间无消息直接断开连接");
				break;
			case WRITER_IDLE:
				break;
			case ALL_IDLE:
				break;
			default:
				break;
			}
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Channel incoming = ctx.channel();
        if(!incoming.isActive()) {
        	logger.info("客户端:" + ctx.channel().remoteAddress() + " 强制关闭连接");
        }
        ctx.close();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		String deviceId = NettyChannelMap.getKeyByValue(ctx);
		if(deviceId!=null) {
			String channelId = NettyChannelMap.getChannelId(deviceId);
			NettyChannelMap.remove(deviceId);
			if(channelId!=null) {
				nettyMsgResolveService.channelInactive(ctx,deviceId,channelId);
			}
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
		nettyMsgResolveService.resolve(channelHandlerContext, byteBuf);
	}
}
